<?php


namespace app\api\controller\User;


use app\api\controller\BaseController;
use app\api\model\User\UserFansModel;
use app\api\model\User\UserModel;
use app\Utils\Util;

class UserWx extends BaseController
{

    /**
     * 微信获取code
     * @return array
     */
    public function get_authorize_url(){
        $appId = "";
        $scope = "";
        $invite_code = input('param.invite_code',0);
        $redirect_uri = $this->setting['api_url'].'/user/authorize_callback';
        if(!empty($invite_code) && !empty($pid)){
            $redirect_uri .= "?invite_code=".$invite_code;
        }
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appId . '&redirect_uri=' . urlencode($redirect_uri) . '&response_type=code' . '&scope=' . $scope . '&state=' . md5(time()) . '#wechat_redirect';
        return Util::returnJson(self::CODE_SUCCESS,$url,'获取成功');
    }

    /**
     * code回调
     */
    public function authorize_callback(){
        $code = input('param.code');
        $state = input('param.state');
        $invite_code = input('param.invite_code');
        $token =  $this->userWxAdd($code, $invite_code);
        header('location:http://mfjy.shawyo.com/?token='.$token.'&code='. $code.'&state='. $state);
        exit();
    }

    /**
     * 微信授权登录
     * @param $code
     * @param $invite_code
     * @return array|string
     */
    public function userWxAdd($code, $invite_code){
        $res = $this->getOpenID($code);
        $fans_info = UserFansModel::getUserFansWhereJoin([['uf.openid','=',$res['openid']]]);
        if($fans_info){
            //用户已存在更新信息
            $token = md5($fans_info['u_openid'].time());
            $fans_save = [
                'head_img' => $fans_info['headimgurl'],
                'nickname' => $fans_info['nickname'],
                'token' => $token,
                'up_time' => date("Y-m-d H:i:s",time())
            ];
            $user_save = [
                'token' => $token,
                'up_time' => date("Y-m-d H:i:s",time())
            ];
            UserFansModel::updateUserFansWhere([['id','=',$fans_info['u_id']]],$fans_save);
            if(!empty($fans_info['u_uid'])){
                UserModel::updateUserWhere([['id','=',$fans_info['u_uid']]],$user_save);
            }
            return $token;
        }else{
            $result = $this->getUserInfo($res['openid'],$res['access_token']);
            $token = md5(rand().time());;
            if(!empty($invite_code)){
                $agent_user = UserModel::getUserWhere([['invite_code','=',$invite_code]]);
            }
            $fans_data = [
                'type' => 2,
                'parent_uid' => !empty($agent_user) ? $agent_user['id'] : 0,
                'openid'=> $result['openid'],
                'unionid' => $result['unionid'],
                'head_img' => $result['headimgurl'],
                'nickname' => $result['nickname'],
                'token' => $token,
                'up_time' => date('Y-m-d H:i:s',time()),
                'add_time' => date('Y-m-d H:i:s',time()),
            ];
            $fans_id = UserFansModel::addUserFans($fans_data);
            if (!empty($fans_id)) {
                return Util::returnJson(self::CODE_SUCCESS,null,'授权登录成功');
            }else{
                return Util::returnJson(self::CODE_SUCCESS,null,'授权登录失败');
            }
        }
    }

    /**
     * 获取openid
     * @param $code
     * @return mixed
     */
    public function getOpenID($code){
        $appId = "";
        $secret = "";
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appId . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        //通过code换取网页授权access_token
        $data =  file_get_contents($url);
        return json_decode($data,true);
    }

    /**
     * 获取用户信息
     * @param $openid
     * @param $access_token
     * @return mixed
     */
    public function getUserInfo($openid,$access_token){
        $url_name = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $data = file_get_contents($url_name);
        return json_decode($data,true);
    }

}